<template>
  <base-layout
    :dialog-title="dialogTitle"
    :dialog-visible="dialogVisible"
    dialog-width="600px"
    :page-show="pageShow"
    @dialog-close="dialogClose"
  >
    <template #toolPanel />
<!--    <template #searchPanel>-->
<!--    </template>-->
    <template #contentPanel>
      <el-form ref="form" :model="form" label-width="80px" @submit.prevent="onSubmit" style="width:100%;min-width:300px;">
        <el-form-item label="分销商:" prop="useruuid">
          <el-select v-model="form.uid" placeholder="请选择分销商" clearable @change="userChange">
            <el-option value="0" label="全部"  >全部</el-option>
            <el-option
              v-for="item in users"
              :key="item.user.useruuid"
              :label="item.user.username"
              :value="item.user.useruuid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运营商:" prop="busuuid">
          <el-select v-model="form.operatoruid" clearable placeholder="请选择运营商">
            <el-option
              v-for="item in operator"
              :key="item.operatoruid"
              :label="item.operatorname"
              :value="item.operatoruid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型:" prop="busuuid">
          <el-select v-model="form.busCode" clearable placeholder="请选择业务类型">
            <el-option value="0" label="全部">全部</el-option>
            <el-option
              v-for="item in bus"
              :key="item.busuuid"
              :label="item.busname"
              :value="item.busCode">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="账号余额:">
          <span >{{form.downshopbalance}}</span>
        </el-form-item>

        <!--		<el-form-item label="产品名称" prop="productuuid">-->
        <!--			<el-select v-model="form.pid" placeholder="请选择产品" @change="productChange">-->
        <!--				<el-option value="0" label="全部">全部</el-option>-->
        <!--				<el-option-->
        <!--						v-for="item in products"-->
        <!--						:key="item.downprouuid"-->
        <!--						:label="item.productName"-->
        <!--						:value="item.downprouuid">-->
        <!--				</el-option>-->
        <!--			</el-select>-->
        <!--		</el-form-item>-->
        <!--		<el-form-item label="充值金额">-->
        <!--			<el-input v-model="form.amount" :disabled="true"></el-input>-->
        <!--		</el-form-item>-->

        <el-form-item label="充值号码:">
          <el-input  type="textarea" v-model="form.phone" :rows="15"
                     placeholder="批量充值时格式为:号码+空格+面值+空格+数量
			18011112222 100 2
			18900002222 50 1
			15922223333 30 3"  ></el-input>
        </el-form-item>
        <el-form-item label="">
          <span >当日已提交订单数:{{orderNum}}笔,当日合计面值:{{orderMoney}}元</span>
        </el-form-item>
        <!--		<el-form-item label="回调地址">-->
        <!--			<el-input v-model="form.notify"></el-input>-->
        <!--		</el-form-item>-->
        <!--		<el-form-item label="时间戳">-->
        <!--			<el-input v-model="form.ts"></el-input>-->
        <!--		</el-form-item>-->
        <!--<el-form-item label="key">-->
        <!--<el-input v-model="form.key"></el-input>-->
        <!--</el-form-item>-->
        <!--		<el-form-item label="SIGN">-->
        <!--			<el-input v-model="form.sign"></el-input>-->
        <!--		</el-form-item>-->
        <el-form-item label="批次号:">
          <el-input clearable v-model="form.batchNumber"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" round type="primary" v-on:click="onrestBatch">批量充值</el-button>
        </el-form-item>
      </el-form>
    </template>

    <template #dialog>
<!--      <dialog-data-form :value="dialogData"  @operate="handleDataOperate"/>-->
    </template>

  </base-layout>
</template>

<script>
import baseMixin from '@/mixins/base'
import { findAllDownShopInfo , findAllBus, getConfig, restBatch,findOpeProBusShop} from '@/api/utilsapi'
import moment from "moment";
var crypto = require('crypto');

export default {
  name: 'manualRecharge',
  components: {  },
  mixins: [
    baseMixin({
      idName: 'id',
      refresh: '',
      format(res) {
        return res.map(data => {
          return data
        })
      }
    })
  ],
  data() {
    return {
      buttons: [],
      pageShow: true,
      dialogData:{},
      filters: {
        receivedTime:'',
      },
      form: {
        orderId: 'yidongpingtai'+new Date().getTime(),
        uid: '0',
        amount: '',
        downshopbalance:'',
        busCode:'',
        pid: '',
        phone: '',
        notify: '',
        key: '',
        sign:'',
        batchNumber:'',
        operatoruid:'',
        ts:new Date().getTime()
      },
      bus: [],
      users:[],
      orderNum:0,
      orderMoney:0,
      operator:[]
    }
  },
  methods: {
   async findAllBus () {
      let para = {useruuid: ''};
      const result = await findAllBus(para);
      if(result && result.data){
        this.bus = result.data;
      }
    },
    async findAllDownShopInfo(){
      let para = {useruuid: this.$store.getters.useruuid};
      const result = await findAllDownShopInfo(para);
      if(result && result.data){
        this.users = result.data;
      }
    },
    userChange (shopuuid) {
      if(this.users){
        const result = this.users.find(item => {return shopuuid == item.user.useruuid});
        if(result){
          this.form.downshopbalance = result.downshopbalance+" 元";
        }
      }
    },
    async getConfig(){
      let para = {useruuid: this.$store.getters.useruuid};
      const config = await getConfig(para);
      if(config && config.data){
        this.form.orderId = config.data.testorderprefix+new Date().getTime();
        this.form.notify = config.data.testcallbackurl;
      }
    },
    onrestBatch:function(){
      if(this.form.uid == "0" ) {
        this.$message({
          message: "请选择分销商",
          type: 'error'
        });
        return;
      }
      if(this.form.busCode == "0" || this.form.busCode == "" ){
        this.$message({
          message: "请选择业务类型",
          type: 'error'
        });
        return;
      }
      const phones = this.form.phone.split("\n");
      const kongge = phones.find(item =>{ return item == ""});
      if(!kongge && kongge != undefined){
        this.$message({
          message: "格式错误,请仔细检查,如空格",
          type: 'error'
        });
      }else{
        if(phones.length == 0 || phones[0] == ""){
          this.$message({
            message: "号码不能为空",
            type: 'error'
          });
        }else {
          if(this.form.uid == "0" ){
            this.$message({
              message: "请选择分销商",
              type: 'error'
            });
          }else{
            let orderMoney = 0;
            phones.forEach(item => {
              const ph = item.indexOf(" ") != -1 ? item.split(" ") : item.split("	");
              orderMoney += parseInt(ph[1]);
            });
            console.log("orderMoney:",orderMoney)

            this.$confirm('确认批量提交订单吗？\n当前充值中订单数:'+phones.length+"\n当前充值总面值:"+orderMoney+" 元", '提示', {roundButton:true}).then(() => {
              var orders = [];
              if(phones){
                for(var i = 0 ; i < phones.length; i++){
                  var order = new Object();
                  order.orderId = Math.random().toString(36).substr(2)+new Date().getTime();
                  order.uid = this.form.uid;
                  const ph = phones[i].indexOf(" ") != -1 ? phones[i].split(" ") : phones[i].split("	");
                  if(!ph[0] || !ph[1]){
                    console.log("异常号码:",phones[i])
                    continue;
                  }
                  order.busCode = this.form.busCode;
                  order.phone = ph[0];
                  order.money = ph[1];
                  order.number = ph[2];
                  order.operatoruid = this.form.operatoruid;
                  order.notify = this.form.notify;
                  order.ts = this.form.ts;
                  order.statusremark = this.form.batchNumber;
                  orders.push(order)
                }
              }
              const param = {
                orders : orders,
                useruuid: this.form.uid,
                orderMoney:orderMoney,
                orderNum:phones.length
              }
              restBatch(JSON.stringify(param)).then( datas => {
                let { message, code, data } = datas;
                if (code !== "0") {
                  this.$message({
                    message: message,
                    type: 'error'
                  });
                }else{
                  this.$message({
                    message: "提交成功",
                    type: 'info'
                  });
                }
                this.form.orderId = 'kkspt'+new Date().getTime();
                this.form.ts = new Date().getTime();
                this.form.phone = "";
              });
            });
          }
        }
      }
    },
    async findPageOperator(){
      let para = {
        start: 1,
        pageSize:101,
        operatorname:'',
      };
      findOpeProBusShop(para).then((datas) => {
        let { message, code, data } = datas;
        if (code !== "0") {
          this.showMsg(message,'error')
        } else if(data && data.operator){
          this.operator = data.operator;
        }
      });
    },
  },
  mounted() {
    this.findAllDownShopInfo();
    this.findPageOperator();
    this.findAllBus();
    this.getConfig();
    this.form.batchNumber = moment(new Date(),"YYYY-MM-DD HH:mm:ss").format('YYYYMMDDHHMMSS');
  }
}
</script>
